<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;
use think\Db;
use app\common\extend\Random;
use \think\Cookie;
use app\admin\model\Member as MemberModel;
class Member extends User
{
    /**
     * 会员列表
     */

    public function member()
    {
        $model = new MemberModel();
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        $where='';
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['member_nickname'] = ['like', '%' . $post['keywords'] . '%'];
        }

        if (isset($post['member_remark']) and !empty($post['member_remark'])) {
            $where['member_remark'] = ['like', '%' . $post['member_remark'] . '%'];
        }

        if (isset($post['member_phone']) and !empty($post['member_phone'])) {
            $where['member_phone'] = ['like', '%' . $post['member_phone'] . '%'];
        }

        if (isset($post['member_city']) and !empty($post['member_city'])) {
            $where['member_city'] = ['like', '%' .$post['member_city'] . '%'];
        }

        if (isset($post['admin_cate_id']) and $post['admin_cate_id'] > 0) {
            $where['member_type_id'] = $post['admin_cate_id'];
        }
        if (isset($post['is_apply']) and $post['is_apply'] !='') {
            $where['is_apply'] = intval($post['is_apply'])-10;
        }

        if (isset($post['is_admin']) and $post['is_admin'] !='') {
            $where['is_admin'] = $post['is_admin'];
        }
        if (isset($post['member_id']) and $post['member_id'] !='') {
            $where['member_id'] =['like', '%' . (int)$post['member_id'] . '%'];
        }

        if (isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['creattime'] = [['>=', $min_time], ['<=', $max_time]];
        }

        $where['is_test'] = 0;

//        会员角色
        $info['cate'] = Db::name('member_type')->select();
//        会员数据
        $member = $model->where($where)->order('updatetime desc')->paginate(20);

        foreach ($member as $key=> $value ){

            $value['thumb']=db('attachment')->where('id',$value['thumb'])->field('filepath as url')->find();

            $member_pcode=$value['member_pcode'];
            if($member_pcode){
                $member_user=Db::name('member')->where('member_id',$member_pcode)->field('member_nickname')->find();
                $member[$key]['invitmember']=$member_user['member_nickname'];
            }else{
                $member[$key]['invitmember']='';
            }
        }

        $this->assign('member', $member);
        $this->assign('info', $info);
        $this->assign('wherelist', $post);
        return $this->fetch();
    }

    /**
     * 新增、修改会员信息
     */

    public function addmember()
    {
        $model = new MemberModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            //是修改操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['member_nickname', 'require', '昵称不能为空'],
                    ['member_type_id', 'require', '请选择会员等级'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $basenickname =Db::name('member')->where('member_id', $id)->field('member_nickname')->find();

                if($basenickname['member_nickname']!=$post['member_nickname']){
                    //验证昵称是否存在
                    $nickname = $model->where('member_nickname', $post['member_nickname'])->select();
                    if (!empty($nickname)) {
                        return $this->error('提交失败：该昵称已被占用');
                    }
                }

                $post['updatetime']=time();
                $post['is_apply']=2;
               $me= $model->allowField(true)->save($post, ['member_id' => $id]);

                if (false == $me) {
                    return $this->error('修改失败');
                } else {

                    return $this->success('修改会员信息成功', 'admin/member/member');
                }
            } else {
                //非提交操作
                $info['admin'] = $model->where('member_id', $id)->find();
                $info['cate'] = Db::name('member_type')->where('type_status', 1)->select();
//                var_dump($info);exit();
                $this->assign('info', $info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                if(empty($post['member_phone'])&&empty($post['member_email'])){
                    return $this->error('提交失败：手机号或邮箱至少填一个');
                }
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['member_nickname', 'require', '昵称不能为空'],
                    ['member_password', 'require|confirm', '密码不能为空|两次密码不一致'],
                    ['member_password_confirm', 'require', '重复密码不能为空'],
                    ['member_type_id', 'require', '请选择会员等级'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }



                if($post['member_phone']){
                    //验证用户名是否存在
                    $name = $model->where('member_phone', $post['member_phone'])->select();

                    if (!empty($name)) {
                        return $this->error('提交失败：手机号已被注册');
                    }
                }


                if($post['member_email']){
                    //验证邮箱是否存在
                    $name = $model->where('member_email', $post['member_email'])->select();

                    if (!empty($name)) {
                        return $this->error('提交失败：邮箱已被注册');
                    }
                }


                //验证昵称是否存在
                $nickname = $model->where('member_nickname', $post['member_nickname'])->select();

                if (!empty($nickname)) {
                    return $this->error('提交失败：该昵称已被占用');
                }
                //密码处理
                $post['member_password'] = password($post['member_password']);
                $post['creattime']=time();
                $post['updatetime']=time();

                if (false == $model->allowField(true)->save($post)) {
                    return $this->error('添加会员失败');
                } else {
                    return $this->success('添加会员成功', 'admin/member/member');
                }
            } else {
                //非提交操作
                $info['cate'] = Db::name('member_type')->where('type_status', 1)->select();
                $this->assign('info', $info);
                return $this->fetch();
            }
        }
    }


    /**
     * 禁用/启用会员
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $model = new MemberModel();
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $status = $this->request->has('status') ? $this->request->param('status', 0, 'intval') : 0;
            if($status){
                $data['member_status'] =$status;
            }
            if($status==2){
                $msg='禁用';
            }else{
                $msg='启用';
            }
            $data['updatetime']=time();
            if (false == $model->allowField(true)->save($data, ['member_id' => $id])) {
                return $this->error($msg.'失败');
            } else {
                return $this->success($msg.'会员成功', 'admin/member/member');
            }
        }
    }


    /**
     * 提现
     */
    public function extract()
    {
        $model = new MemberModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //获取管理员id
        $adminid = Cookie::get('admin');
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['accounts_money', 'require', '提现金额不能为空'],

            ]);

            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }

            $membermoney=Db::name('member')->where('member_id', $id)->field('member_money')->find();
            $accounts_money=$post['accounts_money'];
            if($membermoney['member_money']==0||$membermoney['member_money']-$accounts_money<0){
                return $this->error('提现失败,可提现余额不足');
            }

            $postaccounts['member_id']=$id;
            $postaccounts['accounts_money']=$accounts_money;
            $postaccounts['business_way']=2;
            $postaccounts['description']=$post['description'];
            $postaccounts['creattime']=date("YmdHis");
            $postaccounts['admin_id']=$adminid;
            $data['member_money']=$membermoney['member_money']-$accounts_money;

            Db::startTrans(); //启动事务
            try {
                //写入putforward提现记录
                Db::name('putforward')->insert([
                    'member_id'=>$id,
                    'money'=>$accounts_money,
                    'state'=>2,//直接审核通过
                    'time'=>time(),
                    'uptime'=>time(),
                    'adminid'=>Cookie::get('admin')
                ]);
                //写入资金流水
                Db::name('accounts')->insert($postaccounts);
                //修改客户金额
                $model->allowField(true)->save($data, ['member_id' => $id]);

                Db::commit(); //提交事务
                return $this->success('提现成功', 'admin/member/member');
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error('提现失败');
            }
        } else {
            //非提交操作
            $info =$model->where('member_id', $id)->field('member_nickname,member_money,member_id')->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //模拟用户发送验证码【不发送短信】
    public function fakeSendCode()
    {
        $post = request()->post();
        $member_id = $post['member_id']??0;
        $member = db('member')->find($member_id);
        if(empty($member_id) || empty($member)){
            return $this->error('会员信息不存在');
        }
        $telphone = $member['member_phone']??"";
        if(empty($telphone)) return $this->error('会员手机号为空');

        $exist_code = db('code')->where('telphone',$telphone)->find();
        if (!empty($exist_code)){
            $code = $exist_code['code'];
        }else{
            $code = Random::numeric();
            db('code')->insert([
                'code'=>$code,
                'telphone'=>$telphone,
                'time'=>time(),
            ]);
        }

        //记录日志

        $this->writeFakeAdminData($telphone,$code);
        return $this->success('获取成功，验证码是：'.$code);
    }

    //设置用户账号是否为管理员
    public function updateMemberAdmin()
    {
        $post = request()->post();
        $member_id = $post['member_id']??0;
        $member = db('member')->find($member_id);
        if(empty($member_id) || empty($member)){
            return $this->error('会员信息不存在');
        }

        $is_admin = $post['admin']??"";
        if($is_admin==="") return $this->error('操作有误');

        $res = db('member')->where(['member_id'=>$member_id])->update(['is_admin'=>$is_admin]);
        if($res!==false){
            return $this->success('修改成功');
        }else{
            return $this->error('修改失败');
        }
    }

    //记录核价数据
    public function writeFakeAdminData($telphone,$code)
    {
        $dir = APP_PATH.'logs/fake';
        if(!is_readable($dir)){
            is_file($dir) or mkdir($dir,0755);
        }
        $log = 'fake_log';
        if(is_file($dir.'/'.$log)){
            $filesize = filesize($dir.'/'.$log);
            if($filesize>1048576){//设置log文件大小为1mb
                rename($dir.'/'.$log,$dir.'/'.$log."".date('YmdH',time()));
            }
        }
        $admin_id = Cookie::get('admin');
        $admin = db('admin')->find($admin_id);
        $admin_name = $admin['nickname']??'';
        $content = 'ID为【'.$admin_id.'】的管理员【'.$admin_name.'】获取账号【'.$telphone.'】的验证码为【'.$code.'】';
        $result = file_put_contents($dir.'/'.$log,(date('Y-m-d h:i:s',time()))."  ".$content."\r\n",FILE_APPEND);
        return $result;
    }
}
